<template>
  <div class="w-full h-screen box-border relative overflow-hidden">
    <van-nav-bar 
      left-arrow 
      :title="$t('pageTitle.welfare')" 
      @click-left="router.back()" 
      safe-area-inset-top 
    />
    <van-image width="100%" height="30vh" :src="bg" />
    <van-row class="text-[14px]">
      <van-col :span="12" class="border-b-[1px] py-3">
        <div class="text-center">
          <span>{{ $t('donated') }}</span>
          <span>: </span>
          <span class="text-red-600 ml-2">
            {{ donateData.totalMoney || 0 }}
          </span>
          <span>{{ $t('currency') }}</span>
        </div>
        <div class="text-center">
          <span>{{ $t('donationCount') }}</span>
          <span>: </span>
          <span class="text-red-600 ml-2">
            {{ donateData.count || '0' }}
          </span>
          <span>{{ $t('count') }}</span>
        </div>
      </van-col>
      <van-col :span="12">
        <div class="flex-1 flex h-full justify-center items-center text-center bg-red-500 text-white">
          {{ $t('btnText.myDonation') }}
        </div>
      </van-col>
    </van-row>
    <div class="mx-6 my-4 text-emerald-600 text-[14px]">
      <div>{{ $t('donationText.donationTitle') }}</div>
      <div class="indent-2">
        {{ $t('donationText.donationText-1') }}
      </div>
      <div class="indent-2">
        {{ $t('donationText.donationText-2') }}
      </div>
    </div>
    <van-row justify="center" align="center" class="!text-center !mt-12">
      <van-col span="12">
        <van-button plain round type="danger" class="!px-8">
          {{ $t('btnText.inviteFriends') }}
        </van-button>
      </van-col>
      <van-col span="12">
        <van-button round type="danger" class="!px-12" @click="show = true">
          {{ $t('btnText.donationNow') }}
        </van-button>
      </van-col>
    </van-row>
    <van-number-keyboard safe-area-inset-bottom />
    <van-popup v-model:show="show" round class="box-border pt-2 pb-6 px-16">
      <van-icon
        name="close" 
        color="#969799" 
        size="1.4rem" 
        class="absolute right-2 top-2 clear-both" 
        @click="closePopup()"
      />
      <div class="text-center">
        {{ $t('pageTitle.donation') }}
      </div>
      <div class="mt-4 mb-2 text-[14px] text-[#969799] text-center">
        <span>{{ $t('balance') }}</span>
        <span>: </span>
        <span>{{ balance }}</span>
        <span>{{ $t('currency') }}</span>
      </div>
      <van-config-provider :theme-vars="themeVars">
        <van-form @submit="submit" ref="formRef">
          <div class="flex justify-center items-center">
            <van-cell-group inset>
              <van-field 
                label=" "
                v-model="money"  
                name="money" 
                type="digit"
                clearable
                label-width="0rem"
                :placeholder="$t('placeholder.enterPrice')" 
                :rules="moneyRules" 
              />
            </van-cell-group>
            <div class="ml-2">{{ $t('currency') }}</div>
          </div>
          <div class="mt-8 mb-2">
            <van-button 
              round 
              block 
              :loading="loading"
              type="primary" 
              native-type="submit" 
              color="linear-gradient(to right, #ff6034, #ee0a24"
            >
              <div class="text-white">
                {{ $t('btnText.donationNowMoney') }}
              </div>
            </van-button>
          </div>
        </van-form>
      </van-config-provider>
    </van-popup>
  </div>
</template>
<script setup lang="ts">
import bg from "@/assets/images/gift-bg.jpg"

import { showToast, type FieldRule, type FormInstance } from "vant"

import { useRouter } from "vue-router"

import { useI18n } from 'vue-i18n'

import { useUserStore } from "@/store/user"

import { Decimal } from "decimal.js"

import { donate, getDonateData } from "@/service/login"

const router = useRouter()

const { t } =  useI18n({ useScope: 'global' })

const user = useUserStore()

onBeforeMount(() => user.loadWallet())

const balance = computed(() => new Decimal((user?.wallet?.balance || 0)).toFixed(2))

const loading = ref<boolean>(false)

const show = ref<boolean>(false)

const formRef = ref<FormInstance>()

const donateData = ref<{ count: number, totalMoney: number }>({
  count: 0,
  totalMoney: 0
})

const loadDonateData = async () => {
  const res = await getDonateData({})

  if(!res.success) return 

  donateData.value = res.data
}

onBeforeMount(() => loadDonateData())

const themeVars = { 
  cellBackground: "#F5F7F9",
  cellGroupInsetRadius: '10px',
  cellVerticalPadding: '8px',
  cellGroupInsetPadding: 0
}

const money = ref<string>()

const closePopup = () => {
  money.value = undefined
  formRef.value?.resetValidation()
  show.value = false
}

const moneyRules: FieldRule[] = [{
  required: true, message: t('placeholder.enterPrice'), trigger: 'onBlur'
}]

const submit = async () => {
  try {
    loading.value = true

    const res = await donate({
      money: money.value!
    })

    loading.value = false

    if(!res.success) return
    
    closePopup()

    await loadDonateData()

    await user.loadWallet()
    
    showToast(res.message)

  } catch(err){
      loading.value = false
    throw err
  }
}
</script>

<style lang="less" scoped>
:deep(.van-field__error-message) {
  position: absolute;
  top: 0;
  left: 56%;
}
</style>
